package com.cskaoyan.service;

import com.cskaoyan.mapper.AccountMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.TransactionCallback;
import org.springframework.transaction.support.TransactionCallbackWithoutResult;
import org.springframework.transaction.support.TransactionTemplate;

@Service
public class AccountServiceImpl implements AccountService{

    @Autowired
    AccountMapper accountMapper;

    @Autowired
    TransactionTemplate transactionTemplate;

    public void transfer(Integer fromId, Integer destId, Integer money) {
        Integer fromMoney = accountMapper.selectMoneyById(fromId);
        Integer destMoney = accountMapper.selectMoneyById(destId);

        fromMoney -= money;
        destMoney += money;

        Integer finalDestMoney = destMoney;
        Integer finalFromMoney = fromMoney;
        /*Object execute = transactionTemplate.execute(new TransactionCallback<Object>() {
            @Override
            public Object doInTransaction(TransactionStatus transactionStatus) {
                accountMapper.update(fromId, finalFromMoney);
                int i = 1 / 0;
                accountMapper.update(destId, finalDestMoney);
                //doInTransaction方法的返回值会给到TransactionTemplate的execute方法
                return "aaa";
            }
        });*/
        //如果增加事务的内容不需要返回值，可以使用TransactionCallbackWithoutResult
        transactionTemplate.execute(new TransactionCallbackWithoutResult() {
            @Override
            protected void doInTransactionWithoutResult(TransactionStatus transactionStatus) {
                accountMapper.update(fromId, finalFromMoney);
                int i = 1 / 0;
                accountMapper.update(destId, finalDestMoney);
            }
        });
    }
}
